package com.example.cloud.util.security;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;

/**
 * HMac SHA256加密
 *
 * @author tongyufu
 */
public class HMacUtil {

    /**
     * 加密
     *
     * @param content 要加密的内容
     * @param secret 密钥
     * @return 加密后字符串
     */
    public static String encode(String content, String secret) {
        try {
            //Security.addProvider(new BouncyCastleProvider());
            SecretKey secretKey = new SecretKeySpec(secret.getBytes("UTF8"), "HmacSHA256");
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            byte[] digest = mac.doFinal(content.getBytes("UTF-8"));
            return new HexBinaryAdapter().marshal(digest);
        } catch (Exception e) {
            throw new RuntimeException("加密异常");
        }
    }

    /**
     * 解密
     *
     * @param content 要加密的内容
     * @param secret 密钥
     * @return 解密后字符串
     */
    public static String decode(String content, String secret) {
        try {
            //Security.addProvider(new BouncyCastleProvider());
            SecretKey secretKey = new SecretKeySpec(secret.getBytes("UTF8"), "HmacSHA256");
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            byte[] digest = mac.doFinal(content.getBytes("UTF-8"));
            return new String(new HexBinaryAdapter().unmarshal(content), "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("加密异常");
        }
    }
}
